package org.msb.accentis.gui.models;

import java.math.BigDecimal;

import javax.swing.table.AbstractTableModel;

import org.msb.accentis.data.pojo.Account;
import org.msb.accentis.data.pojo.Category;
import org.msb.accentis.data.pojo.Individual;
import org.msb.accentis.data.pojo.Payee;
import org.msb.accentis.gui.Resources;
import org.msb.accentis.gui.transactions.ComplexTransactionAdapter;

public class TransactionDetailTableModel extends AbstractTableModel {

	private static final Class<?>[] COLUMN_CLASSES = { Account.class, Payee.class, Category.class, Category.class, Individual.class, String.class, BigDecimal.class };

	private static final String[] COLUMN_NAMES = { "account", "payee", "category", "subcategory", "individual", "description", "amount" };
	
	private ComplexTransactionAdapter adaptedTransaction;

	public TransactionDetailTableModel() {
	}

	public void setTransaction(ComplexTransactionAdapter transaction) {
		adaptedTransaction = transaction;
		fireTableDataChanged();
	}
	
	@Override
	public int getRowCount() {
		if (null == adaptedTransaction)
			return 0;
		
		return adaptedTransaction.getDetailCount();
	}

	@Override
	public int getColumnCount() {
		return 7;
	}

	@Override
	public Object getValueAt(int row, int col) {
		if (null == adaptedTransaction)
			return null;
		
		return adaptedTransaction.getValueAt(row, col);
	}

	@Override
	public void setValueAt(Object value, int row, int col) {
		if (null != adaptedTransaction)
			adaptedTransaction.setValueAt(row, col, value);
	}

	@Override
	public String getColumnName(int column) {
		return Resources.getInstance().getString("transactiondetailstable." + COLUMN_NAMES[column] + "column.name");
	}

	@Override
	public Class<?> getColumnClass(int column) {
		return COLUMN_CLASSES[column];
	}
	
	public void addDetail() {
		if (null == adaptedTransaction)
			return;
		
		adaptedTransaction.addDetail();
		
		fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
	}
	
	public void removeDetails(int[] rows) {
		if (null == adaptedTransaction)
			return;
		
		for (int i = rows.length - 1; 0 <= i; --i) {
			adaptedTransaction.removeDetail(rows[i]);
			
			fireTableRowsDeleted(rows[i], rows[i]);
		}
	}

	@Override
	public boolean isCellEditable(int row, int col) {
		return (col == 3 && null != getValueAt(row, 2)) || (col != 3);
	}
}
